package com.wunong.smart.collection.domain.state.operation.impl;

import com.wunong.smart.collection.application.context.CollectionContext;
import com.wunong.smart.collection.application.request.CancelCollectionRequest;
import com.wunong.smart.collection.client.enums.CollectionStatusEnum;
import com.wunong.smart.collection.domain.model.CollectionDomain;
import com.wunong.smart.collection.domain.state.operation.AbstractCollectionOperation;
import com.wunong.smart.domain.platform.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 取消收藏
 *
 * @author create by zealot.zt
 */
@Slf4j
@Component
public class CancelCollectionOperation extends AbstractCollectionOperation<CancelCollectionRequest> {

    @Override
    protected void beforeOperate(CollectionContext<CancelCollectionRequest> context) {
        if (!collectionStateService.canCancel(context.getRequest(), context.getDomain())) {
            throw new ServiceException("暂不支持取消收藏");
        }
    }

    @Override
    protected Object doOperate(CollectionContext<CancelCollectionRequest> context) {
        CollectionDomain domain = context.getDomain();

        // 已取消收藏，直接返回
        if (domain.isCanceled()) {
            log.info("user cancel collect skip, userId:{}, collectId:{}", domain.getUserId(), domain.getId());
            return domain.getId();
        }

        domain.setStatusEnum(CollectionStatusEnum.CANCELED);
        collectionRepository.update(domain);
        log.info("user cancel collect success, userId:{}, collectId:{}", domain.getUserId(), domain.getId());
        return domain.getId();
    }

    @Override
    public Class<CancelCollectionRequest> getRequestClass() {
        return CancelCollectionRequest.class;
    }

}
